package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 购物车拦截器 gl:即在执行所有购物车的controller之前 先执行拦截器的逻辑
 * 
 * 比如在CartController中 可以用
 * CartInterceptor.threadLocal.get() 获取UserInfoTo 看一下当前用户是不是临时用户即是不是在没有
 * 登录前在给购物车添加商品
 */
public class CartInterceptor implements HandlerInterceptor {
    //gl: 同一个线程中 共享UserInfoTo数据信息
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();
    /**     
     * 请求前拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override  //gl C239-13:33
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        UserInfoTo userInfoTo = new UserInfoTo();

        HttpSession session = request.getSession();
        MemberResponseVo member = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member != null) {
            //登录了
            userInfoTo.setUserId(member.getId());

        }
        Cookie[] cookies = request.getCookies(); //16:33 从cookie里面获取数据看看是不是临时用户
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setIsTempUser(true);
                }
            }

        }
        //c239 29:11 如果没有临时用户，一定要分配一个临时用户
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }

      //目标方法执行之前
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 后执行 
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     */
    @Override  //如果是临用户的话， 还得让浏览器以cookie的方式保存起来.
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
     Object handler, ModelAndView modelAndView) {
        UserInfoTo userInfoTo = threadLocal.get();

        if(!userInfoTo.getIsTempUser()){
            //持续延长临时用户的过期时间
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
